<?php

namespace app\api\controller;

use app\admin\model\Member;
use app\admin\model\MemberEarningDetail;
use app\admin\model\MyDinosaur;
use think\Db;
use think\facade\Lang;
use app\common\Status;
use think\response\Json;
use app\api\service\BlockChain;
use app\admin\model\DinosaurList;

class User extends Base
{
    /**
     * @Title: dinosaur
     * @Describe 恐龙集市
     * @return Json
     * @author lijunwei
     * @Date 2021/12/14 13:25
     */
    public function dinosaurBazaar()
    {
        $level = intval(input('param.level', 9));
        $page = intval(input('param.page', 1));
        $size = intval(input('param.size', 15));
        $name = input('param.name');
        if (isset($level) && $level != 9 && ($level < 0 || $level > 2)) {
            return returnJson(Status::FAILED, Lang::get('level_beyond'));
        }
        if (!empty($name)) {
            $arr = explode("_", $name);
            $ji = $arr[1];
        }
        // 如果级别和恐龙名称都存在，则判断是不是该级别的恐龙，如果不是则返回空数据
        if (isset($level) && isset($ji) && $level != 9 && $level != $ji) {
            return returnJson(Status::SUCCESS, '', []);
        }
        if (isset($ji)) {
            $level = $ji;
        }
        // 测试环境使用 start
        $info = (new BlockChain())->info();
        $str = 'DinosaurLevel' . $level;
        // 测试环境使用 end
        if (isset($level) && $level != 9) {
            $config = config('app.dinosaur');
//            $where = ['on_sale' => 1, 'contract_address' => $config[$level]];
            $where = ['on_sale' => 1, 'contract_address' => $info[$str]];
        } else {
            $where = ['on_sale' => 1];
        }

        $filed = ['id', 'order_number', 'contract_address', 'owner', 'token_id', 'price', 'residue_num'];
        $list = (new DinosaurList())->getPage($where, $page, $size, $filed);
        if (!$list) {
            return returnJson(Status::FAILED, Lang::get('no_data'));
        }
        $result = [];
        foreach ($list['data'] as $key => $item) {
            $k = array_search($item['contract_address'], $info);
            $number = substr($k, -1);
//            $configLevel = config('app.dinosaur_level');
//            if (!isset($configLevel[$item['contract_address']])) {
//                return returnJson(Status::FAILED, Lang::get('address_error'));
//            }
//            $level = $configLevel[$item['contract_address']];
//            $dinosaur = $this->dinosaurInfo($level);
            $dinosaur = $this->dinosaurInfo((int)$number);
            $result[$key] = [
                'id' => $item['id'],
                'orderNumber' => $item['order_number'],
                'contractAddress' => $item['contract_address'],
                'owner' => $item['owner'],
                'tokenId' => $item['token_id'],
                'price' => $item['price'],
                'residueNum' => $item['residue_num'],
                'name' => $dinosaur['name'],
                'nameEn' => $dinosaur['nameEn'],
                'cate' => $dinosaur['cate'],
                'powerValue' => $dinosaur['powerValue'],
                'attack' => $dinosaur['attack'],
                'defense' => $dinosaur['defense'],
                'physicalStrength' => $dinosaur['physicalStrength'],
                'description' => $dinosaur['description'],
                'level' => $dinosaur['level'],
                'image' => $dinosaur['image'],
            ];
        }

        return returnJson(Status::SUCCESS, '', $result);
    }

    /**
     * @Title: buySuccess
     * @Describe 购买成功调用
     * @author lijunwei
     * @Date 2021/12/23 11:36
     */
    public function buySuccess()
    {
        (new BlockChain())->dinosaurBazaar();

        return returnJson(Status::SUCCESS, '', []);
    }

    /**
     * @Title: dinosaurInfo
     * @Describe 获取恐龙详情
     * @param $level
     * @return mixed
     * @author lijunwei
     * @Date 2021/12/17 18:41
     */
    public function dinosaurInfo($level)
    {
        $path = ROOT_PATH . "public/nft/{$level}/metadata/json/0.json";
        $string = file_get_contents($path);
        return json_decode($string, true);
    }

    /**
     * @Title: leaderboard
     * @Describe 恐龙数、金币、探险数排行榜
     * @author lijunwei
     * @Date 2021/12/19 12:02
     */
    public function leaderboard()
    {
        $type = intval(input('param.type', 0));
        $page = intval(input('param.page', 1));
        $size = intval(input('param.size', 15));
        $userAddress = trim(input('param.userAddress'));
        if (empty($userAddress)) {
            return returnJson(Status::FAILED, Lang::get('address_require'));
        }
        if ($type == 0) {
            $order = "dinosaur_num";
            $filed = ['id', 'user_address', 'dinosaur_num'];
            $where[] = ['dinosaur_num', '>', 0];
        } elseif ($type == 1) {
            $order = "gold_coin_num";
            $filed = ['id', 'user_address', 'gold_coin_num'];
            $where[] = ['gold_coin_num', '>', 0];
        } elseif ($type == 2) {
            $order = "adventure_num";
            $filed = ['id', 'user_address', 'adventure_num'];
            $where[] = ['adventure_num', '>', 0];
        } else {
            $order = "dinosaur_num";
            $filed = ['id', 'user_address', 'dinosaur_num'];
            $where[] = ['dinosaur_num', '>', 0];
        }
        $list = (new Member())->memberList($where, $page, $size, $filed, $order);
        $results = (new Member())->getAll($where, $filed, $order);
        $num = 0;
        foreach ($results as $key => $value) {
            if ($userAddress == $value['user_address']) {
                $num = $key + 1;
            }
        }
        $res['rank'] = $num;
        $res['list'] = $list;

        return returnJson(Status::SUCCESS, '', $res);
    }

    /**
     * @Title: buyDinosaur
     * @Describe 购买成功调用接口 （更新我的恐龙数据）
     * @return Json
     * @author lijunwei
     * @Date 2021/12/24 10:27
     */
//    public function buyDinosaur()
//    {
//        // 给我的恐龙接口生成数据
//        Db::startTrans();
//        try {
//            $post = $this->request->post();
//            // 验证参数
//            $var = [$post['ownerAddress'], $post['userAddress'], $post['contract'], $post['tokenId']];
//            list($ownerAddress, $userAddress, $contract, $tokenId) = $var;
//            if (!isset($ownerAddress)) {
//                return returnJson(Status::FAILED, Lang::get('seller_require'));
//            }
//            if (!isset($userAddress)) {
//                return returnJson(Status::FAILED, Lang::get('buyers_require'));
//            }
//            if (!isset($contract)) {
//                return returnJson(Status::FAILED, Lang::get('contract_require'));
//            }
//            if (!isset($tokenId)) {
//                return returnJson(Status::FAILED, Lang::get('token_require'));
//            }
//            // 卖家删除
//            $where = ['user_address' => $ownerAddress, 'contract_address' => $contract, 'dinosaur_no' => $tokenId];
//            MyDinosaur::getInstance()->where($where)->delete();
//            // 获取恐龙集市里面其它数据
//            $info = DinosaurList::getInstance()->getOne(['owner' => $ownerAddress, 'contract_address' => $contract, 'token_id' => $tokenId]);
//            // 买家新增
//            $data = [
//                'user_address' => $userAddress,
//                'contract_address' => $contract,
//                'dinosaur_no' => $tokenId,
//                'order_number' => $info['order_number'],
//                'price' => $info['price'],
//                'residue_num' => $info['residue_num'],
//            ];
//            MyDinosaur::getInstance()->insertGetId($data);
//
//            // 生成集市列表数据使用
//            (new BlockChain())->dinosaurBazaar();
//
//            Db::commit();
//            return returnJson(Status::SUCCESS, '', []);
//        } catch (\Exception $e) {
//            Db::rollback();
//            errorLog($this->action, $e);
//            return returnJson(Status::SYSTEM_ERROR, lang('system_error'));
//        }
//    }

    /**
     * @Title: myDinosaur
     * @Describe 我的恐龙
     * @return Json
     * @author lijunwei
     * @Date 2021/12/23 16:15
     */
//    public function myDinosaur()
//    {
//        $level = intval(input('param.level', 9));
//        $page = intval(input('param.page', 1));
//        $size = intval(input('param.size', 15));
//        $onSale = input('param.onSale');
//        $name = input('param.name');
//        $userAddress = input('param.userAddress');
//        if (!isset($userAddress)) {
//            return returnJson(Status::FAILED, Lang::get('address_require'));
//        }
//        if (isset($level) && $level != 9 && ($level < 0 || $level > 2)) {
//            return returnJson(Status::FAILED, Lang::get('level_beyond'));
//        }
//        if (!empty($name)) {
//            $arr = explode("_", $name);
//            $ji = $arr[1];
//        }
//        // 如果级别和恐龙名称都存在，则判断是不是该级别的恐龙，如果不是则返回空数据
//        if (isset($level) && isset($ji) && $level != 9 && $level != $ji) {
//            return returnJson(Status::SUCCESS, '', []);
//        }
//        if (isset($ji)) {
//            $level = $ji;
//        }
//        // 测试环境使用 start
//        $info = (new BlockChain())->info();
//        $str = 'DinosaurLevel' . $level;
//        // 测试环境使用 end
//        $where = ['user_address' => $userAddress];
//        if (isset($level) && $level != 9) {
////            $config = config('app.dinosaur');
////            $where = ['on_sale' => 1, 'contract_address' => $config[$level]];
//            $where['contract_address'] = $info[$str];
//        }
//        if (isset($onSale) && in_array($onSale, [0, 1])) {
//            $where['on_sale'] = (int)$onSale;
//        }
//        $filed = ['contract_address', 'dinosaur_no', 'on_sale', 'order_number', 'price', 'residue_num'];
//        $list = (new MyDinosaur())->getPage($where, $page, $size, $filed, 'order desc');
//        if (!$list) {
//            return returnJson(Status::FAILED, Lang::get('no_data'));
//        }
//        $result = [];
//        $newArray = array();
//        foreach ($list['data'] as $v) {
//            $newArray[$v['contract_address']][] = $v;
//        }
//        foreach ($newArray as $key => $value) {
//            $key = $this->getLevel($key);
//            foreach ($value as $v => $item) {
//                $k = array_search($item['contract_address'], $info);
//                $number = substr($k, -1);
////            $configLevel = config('app.dinosaur_level');
////            if (!isset($configLevel[$item['contract_address']])) {
////                return returnJson(Status::FAILED, Lang::get('address_error'));
////            }
////            $level = $configLevel[$item['contract_address']];
////            $dinosaur = $this->dinosaurInfo($level);
//                $dinosaur = $this->dinosaurInfo((int)$number);
//                $result[$key][$v] = [
//                    'contractAddress' => $item['contract_address'],
//                    'dinosaurNo' => $item['dinosaur_no'],
//                    'onSale' => $item['on_sale'],
//                    'orderNumber' => $item['order_number'],
//                    'price' => $item['price'],
//                    'residueNum' => $item['residue_num'],
//                    'name' => $dinosaur['name'],
//                    'nameEn' => $dinosaur['nameEn'],
//                    'cate' => $dinosaur['cate'],
//                    'powerValue' => $dinosaur['powerValue'],
//                    'attack' => $dinosaur['attack'],
//                    'defense' => $dinosaur['defense'],
//                    'physicalStrength' => $dinosaur['physicalStrength'],
//                    'description' => $dinosaur['description'],
//                    'level' => $dinosaur['level'],
//                    'image' => $dinosaur['image'],
//                ];
//            }
//        }
//
//        return returnJson(Status::SUCCESS, '', $result);
//    }

    /**
     * @Title: getLevel
     * @Describe 根据合约的值获取合约的key
     * @param $contract_address
     * @return int
     * @author lijunwei
     * @Date 2021/12/23 17:36
     */
//    public function getLevel($contract_address)
//    {
//        $info = (new BlockChain())->info();
//        // 根据值获取key
//        $key = array_search($contract_address, $info);
//        return (int)substr($key, -1);
//    }

    /**
     * @Title: earnings
     * @Describe 今日收益/累计收益
     * @author lijunwei
     * @Date 2022/1/4 16:50
     */
    public function earnings()
    {
        $userAddress = input('param.userAddress');
        if (!isset($userAddress)) {
            return returnJson(Status::FAILED, Lang::get('address_require'));
        }
        // 显示它的下级B/C两个用户【给他带来的】收益  直接查询MemberEarningDetail表里面pid用户的收益就可以了
        // 1 获取当天收益
        $start_time = strtotime(date("Y-m-d", time()));
        $end_time = $start_time + 60 * 60 * 24;
        $where = ['start_time' => $start_time, 'end_time' => $end_time, 'pid' => $userAddress];
        $today = MemberEarningDetail::getInstance()->getSumByBetween($where, 'earning');
        $total = MemberEarningDetail::getInstance()->getSum(['pid' => $userAddress], 'earning');
        $sql = "SELECT SUM(earning) AS earnings, user_address FROM dn_member_earning_detail WHERE pid = '" .
            $userAddress . "'";
        $sql .= " group by user_address";
        $total_group = Db::query($sql);

        $result = ['todayEarning' => $today, 'totalEarning' => $total, 'list' => $total_group];
        return returnJson(Status::SUCCESS, '', $result);
    }
}
